package org.vosk;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;

import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.*;


/**
 * 测试 文件转语音
 *
 * @author YZD
 */
@Slf4j
public class DecoderUtil {

    public static synchronized Recognizer recognizer() {
        Model model = null;
        try {
            model = new Model(ResourceUtils.getFile("classpath:model").getPath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return new Recognizer(model, 16000);
    }


    public static void main(String[] argv) throws IOException, UnsupportedAudioFileException {

        LibVosk.setLogLevel(LogLevel.INFO);

        try (Model model = new Model(ResourceUtils.getFile("classpath:model").getPath());
             InputStream ais = AudioSystem.getAudioInputStream(new BufferedInputStream(new FileInputStream(ResourceUtils.getFile("classpath:test.wav"))));
             Recognizer recognizer = new Recognizer(model, 16000)) {

            int bytes;
            byte[] b = new byte[4096];
            while ((bytes = ais.read(b)) >= 0) {
                if (recognizer.acceptWaveForm(b, bytes)) {
                    log.info(recognizer.getResult());
                } else {
                    log.info(recognizer.getPartialResult());
                }
            }

/*            File file = ResourceUtils.getFile("classpath:test.wav");
            FileInputStream stream = new FileInputStream(file);
            byte[] b = new byte[stream.available()];
            int read = stream.read(b);
            recognizer.acceptWaveForm( b,read);*/

            log.info(recognizer.getFinalResult());
        }
    }
}
